﻿@model int?

@using SmartStore.Core;
@using SmartStore.Web.Framework.UI;
@using SmartStore.Utilities;

@functions {
	bool? _minimalMode = null;
	string _fieldName = null;
	int _entityId = 0;
	string _entityName = null;
	string _fileTypes = null;

	private bool MinimalMode
	{
		get
		{
			if (!_minimalMode.HasValue)
			{
				_minimalMode = ViewData.ContainsKey("minimalMode") ? ViewData["minimalMode"].Convert<bool>() : false;
			}
			return _minimalMode.Value;
		}
	}

	private string FieldName
	{
		get
		{
			if (_fieldName == null)
			{
				_fieldName = ViewData.ContainsKey("fieldName") ? ViewData["fieldName"].Convert<string>() : ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty);
			}
			return _fieldName;
		}
	}

	private int EntityId
	{
		get
		{
			if (_entityId == 0)
			{
				_entityId = ViewData.ContainsKey("entityId") ? ViewData["entityId"].Convert<int>() : 0;
			}
			return _entityId;
		}
	}

	private string EntityName
	{
		get
		{
			if (_entityName == null)
			{
				_entityName = ViewData.ContainsKey("entityName") ? ViewData["entityName"].Convert<string>() : ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty);
			}
			return _entityName;
		}
	}

	private string FileTypes
	{
		get
		{
			if (_fileTypes == null)
			{
				_fileTypes = ViewData.ContainsKey("fileTypes") ? ViewData["fileTypes"].Convert<string>() : "";
			}
			return _fileTypes;
		}
	}
}

@{
    var random = CommonHelper.GenerateRandomInteger();
    var clientId = "download-editor-" + random;
    var downloadService = EngineContext.Current.Resolve<SmartStore.Services.Media.IDownloadService>();
    var download = downloadService.GetDownloadById(Model.GetValueOrDefault());
    var fileName = string.Empty;
    var initiallyShowUrlPanel = false;
    var hasFile = false;
    var downloadUrl = "";
    if (download != null) {
        downloadUrl = Url.Action("DownloadFile", "Download", new { downloadId = download.Id });
        initiallyShowUrlPanel = !MinimalMode && download.UseDownloadUrl;
        hasFile = !download.UseDownloadUrl;
        fileName = string.IsNullOrWhiteSpace(download.Filename) || download.Filename.IsCaseInsensitiveEqual("undefined")
            ? download.Id.ToString()
            : string.Concat(download.Filename, download.Extension);
    }

    Html.AddScriptParts(true, "~/Administration/Scripts/smartstore.download.js");
}

<div id="@clientId" class="form-row flex-nowrap download-editor@(MinimalMode ? " minimal" : "")"
	 data-download-id="@Model.GetValueOrDefault()"
	 data-use-url="@(initiallyShowUrlPanel ? "true" : "false")"
	 data-upload-url="@Url.Action("AsyncUpload", "Download", new { minimalMode = MinimalMode, fieldName = FieldName, entityId = EntityId, entityName = EntityName, area = "Admin" })"
	 data-delete-url="@Url.Action("DeleteDownload", "Download", new { minimalMode = MinimalMode, fieldName = FieldName, entityId = EntityId, entityName = EntityName, area = "Admin" })">

	<input type="hidden" id="@FieldName.SanitizeHtmlId()" name="@FieldName" value="@Model" class="hidden" />

	<div @Html.Attr("class", "col-auto", !MinimalMode || hasFile)>
		<!-- Type Chooser Dropdown -->
		@if (!MinimalMode)
		{
			<div class="btn-group panel-switcher" title='@T("Common.FileUploader.Upload")'>
				<a class="btn btn-secondary btn-icon dropdown-toggle" data-toggle="dropdown" href="#">
					<i class="fa fa-@(initiallyShowUrlPanel ? "globe": "upload") panel-switcher-icon"></i>
				</a>
				<div class="dropdown-menu">
					<a href="#" class="dropdown-item toggle-file@(!initiallyShowUrlPanel ? " disabled" : "")">@T("Common.FileUploader.Upload")</a>
					<a href="#" class="dropdown-item toggle-url@(initiallyShowUrlPanel ? " disabled" : "")">@T("Common.FileUploader.EnterUrl")</a>
					@if (download != null)
					{
						<div class="dropdown-divider"></div>
						<a href="#" class="dropdown-item remove-download">
							<i class="far fa-trash-alt"></i>
							<span>@T("Common.Remove")</span>
						</a>
					}
				</div>
			</div>
		}
		else if (hasFile)
		{
			<a href="#" class="btn btn-danger btn-icon remove-download" title='@T("Common.Remove")'>
				<i class="far fa-trash-alt"></i>
			</a>
		}
	</div>

	<!-- Main Panel -->
	<div class="col panel-upload">
		<!-- FileUpload Panel  -->
		<div class="form-row flex-nowrap panel-file@(initiallyShowUrlPanel ? " hide": "")">
			@if (hasFile)
			{
				<div class="col-auto">
					<div class="form-control-plaintext text-truncate" style="min-width: 180px; max-width: 180px">
						<a href="@downloadUrl" class="filename" title="@fileName">
							@fileName
						</a>
					</div>
				</div>
			}
			<div class="col">
				@(Html.SmartStore().FileUploader()
					.UploadUrl(Url.Action("AsyncUpload", "Download", new { minimalMode = MinimalMode, fieldName = FieldName, entityId = EntityId, entityName = EntityName, area = "Admin" }))
					.AcceptedFileTypes("")
					.IconCssClass(MinimalMode ? "fa fa-upload" : "")
					.ButtonOutlineStyle(hasFile)
					.UploadText(hasFile ? T("Common.Replace").Text : T("Common.Fileuploader.Upload").Text)
					.ShowRemoveButton(false)
					.ShowRemoveButtonAfterUpload(false)
					.OnUploadingHandlerName("onUploading_" + random)
					.OnCompletedHandlerName("onCompleted_" + random)
					.OnUploadCompletedHandlerName("onUploadCompleted_" + random)
				)
			</div>
		</div>

		<!-- URL Panel -->
		@if (!MinimalMode)
		{
			<div class="panel-url" style="display: @(initiallyShowUrlPanel ? "block": "none")">
				<div class="input-group">
					@{ var value = download != null ? download.DownloadUrl : ""; }
					<input type="text" class="download-url-value form-control" value='@value' data-value='@value' />
					<div class="input-group-append">
						<a class="btn btn-outline-secondary save-download-url disabled" href="@Url.Action("SaveDownloadUrl", "Download", new { minimalMode = MinimalMode, fieldName = FieldName, entityId = EntityId, entityName = EntityName, area = "Admin" })">
							<i class="fa fa-check"></i>
							<span>@T("Common.Save")</span>
						</a>
					</div>
				</div>
			</div>
		}
	</div>
</div>

<script>
		window['onUploading_@random'] = function (e, el, data) { }
		window['onCompleted_@random'] = function (e, el, data) { }
		window['onUploadCompleted_@random'] = function (e, el, data) {
			if (data.result.html) {
				el.closest('.download-editor').replaceWith($(data.result.html));
			}
		}

		$(function () {
			$('#@clientId').downloadEditor();
		});
</script>